package org.example.myleet.p563;

import org.example.myleet.Utils.TreeNode;

public class Solution {

    private int tiltSum;

    public int findTilt(TreeNode root) {
        tiltSum = 0;
        if (null != root) {
            dfsGetChildrenValueSum(root);
        }
        return tiltSum;
    }

    private int dfsGetChildrenValueSum(TreeNode node) {
        int leftChildValueSum = 0;
        if (null != node.left) {
            leftChildValueSum = dfsGetChildrenValueSum(node.left);
        }
        int rightChildValueSum = 0;
        if (null != node.right) {
            rightChildValueSum = dfsGetChildrenValueSum(node.right);
        }
        tiltSum += Math.abs(leftChildValueSum - rightChildValueSum);
        return leftChildValueSum + node.val + rightChildValueSum;
    }
}
